<template>
  <div>
    <el-drawer v-model="drawer" title="上传合同附件" :with-header="true">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="文件标题：" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入文件标题" />
        </el-form-item>
        <el-form-item label="文件：">
          <el-upload
            ref="upload"
            class="upload-demo"
            :limit="1"
            action="#"
            :auto-upload="false"
            v-model:file-list="fileList"
            style="width: 280px"
          >
            <template #trigger>
              <el-button type="primary" icon="Upload" :disabled="fileList.length === 1">
                上传文件
              </el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { postContractFileAdd } from '@/api/controller/contract-file-controller/index'
  const drawer = ref(false)
  const fileList = ref([])
  const show = async (id, type) => {
    ruleForm.value = {
      contractId: id,
      type: type === '1' ? 'collection' : 'payment',
      title: null,
    }
    fileList.value = []
    load.value = false
    drawer.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = ref({
    contractId: null,
    type: null,
    title: null,
  })
  const rules = reactive({
    title: [
      { required: true, message: '请输入文件标题', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
  })
  const load = ref(false)
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        if (fileList.value[0]) {
          load.value = true
          const file = new FormData()
          file.append('file', fileList.value[0].raw)
          const result = await postContractFileAdd(ruleForm.value, file, { loading: true })
          if (result.code === 200) {
            ElMessage.success('上传成功')
            await emit('getData')
            drawer.value = false
          }
          load.value = false
        } else {
          ElMessage.warning('请上传文件')
          return false
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>
